import service from "../common/service";
import dateRangUtil from "../common/dateRangUtil"
import { useMainStore } from "@/store/modules/store";

/**
 * @description 获取最新的 EnjoyRDS 值
 * @returns {string} EnjoyRDS
 */
const getEnjoyRDS = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyRDS = enjoyServiceIp?.EnjoyRDS?.split('/Enjoy/Service')[0] || '';
  const EnjoyRMIS = enjoyServiceIp?.EnjoyRMIS?.split('/Enjoy/Service')[0] || '';
  return EnjoyRDS || EnjoyRMIS;
};

/**
 * @description 获取最新的 EnjoyOA 值
 * @returns {string} EnjoyOA
 */
const getEnjoyOA = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
  return EnjoyOA;
};

/**
 * @description 获取最新的 rdsUrl
 * @returns {object} rdsUrl
 */
const getRdsUrl = () => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
  const EnjoyRDS = enjoyServiceIp?.EnjoyRDS?.split('/Enjoy/Service')[0] || '';
  const EnjoyRMIS = enjoyServiceIp?.EnjoyRMIS?.split('/Enjoy/Service')[0] || '';
  const EnjoyMBMMain = enjoyServiceIp?.EnjoyMain?.split('/Enjoy/Service')[0] || '';
  return {
    mainApi: enjoyServiceIp?.EnjoyRMIS ? `${EnjoyRMIS}/Enjoy/Service` : `${EnjoyOA}/main/api/Enjoy/Service`,
    // bcApi: `${EnjoyRDS}/rds-bc/api/Enjoy/Service`,
    // scApi: `${EnjoyRDS}/rds-sc/api/Enjoy/Service`,
    // fcApi: `${EnjoyRDS}/rds-fc/api/Enjoy/Service`,
    apiApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-api/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    bcApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-bc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    scApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-sc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    fcApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-fc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    reportApi: `${EnjoyRDS || EnjoyRMIS}/report/api/Enjoy/Service`,
	mbmApi: `${EnjoyMBMMain}/Enjoy/Service`,
  };
};

const getBillInfo = async (billType) => {
  const mainStore = useMainStore();
  const enjoyServiceIp = mainStore.enjoyServiceIp;
  const EnjoyOA = enjoyServiceIp?.EnjoyOA?.split('/Enjoy/Service')[0] || '';
  const EnjoyRDS = enjoyServiceIp?.EnjoyRDS?.split('/Enjoy/Service')[0] || '';
  const EnjoyRMIS = enjoyServiceIp?.EnjoyRMIS?.split('/Enjoy/Service')[0] || '';
  const EnjoyMBMMain = enjoyServiceIp?.EnjoyMain?.split('/Enjoy/Service')[0] || '';
  const rdsUrl =  {
    mainApi: enjoyServiceIp?.EnjoyRMIS ? `${EnjoyRMIS}/Enjoy/Service` : `${EnjoyOA}/main/api/Enjoy/Service`,
    // bcApi: `${EnjoyRDS}/rds-bc/api/Enjoy/Service`,
    // scApi: `${EnjoyRDS}/rds-sc/api/Enjoy/Service`,
    // fcApi: `${EnjoyRDS}/rds-fc/api/Enjoy/Service`,
    apiApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-api/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    bcApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-bc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    scApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-sc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    fcApi: enjoyServiceIp?.EnjoyRDS ? `${EnjoyRDS}/rds-fc/api/Enjoy/Service` : `${EnjoyRMIS}/Enjoy/Service`,
    reportApi: `${EnjoyRDS}/report/api/Enjoy/Service`,
	mbmApi: `${EnjoyMBMMain}/Enjoy/Service`,
  };
  if (!billType) {
    return null;
  }
  let billInfo = service.getLocalStorage( 'billInfo');
  if (billInfo) {
    return billInfo.find(item => item.c_bill_type == billType);
  }
  const result = await rdsRequest(rdsUrl.bcApi, 'Rds公共服务', 'GetAllBillTypes', '');
  service.addlocalStorage( 'billInfo', result);
  return result.find(item => item.c_bill_type === billType);
};

/**
 * @description rds请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const rdsRequest = async (url, uniqueKey, methodName, objectData = '', billType = '', tag = null ) => {
  const billInfo = await getBillInfo(billType);
  return new Promise((resolve, reject) => {
    let request = {
      url,
      data: {
        UniqueKey: uniqueKey,
        MethodName: methodName,
        ObjectData: objectData,
        BillType: billType,
        Tag: tag,
        BillRangCtrlLink: billInfo?.c_bill_rang_ctrl_link || "C",
        BillRangCtrlMode: billInfo?.c_bill_rang_ctrl_mode || "A",
      },
    };
    service.request(request, (res) => {
      if (res && res.data) {
        if (!res.data.HasException) {
          resolve(res.data.ObjectData);
        } else {
          uni.showToast({
            duration: 3500,
            icon: 'none',
            title: res.data.Exception.Message,
            mask: true,
          });
          reject(res.data.Exception.Message);
        }
      }
    }, () => {
      console.log('请求失败');
      reject('请求失败');
    });
  });
};


/**
 * @description rds请求
 * @param {string} url 请求地址
 * @param {string} uniqueKey 唯一标识
 * @param {string} methodName 方法名
 * @param {object} objectData 请求参数
 * @param {string} billType 单据类型
 * @returns {Promise} Promise
 */
const rdsRequestAsync = async (url, uniqueKey, methodName, objectData = '', billType = '' ) => {
    return new Promise((resolve, reject) => {
      let request = {
        url,
        data: {
          UniqueKey: uniqueKey,
          MethodName: methodName,
          ObjectData: objectData,
          BillType: billType,
        },
      };
      service.request(request, (res) => {
        if (res && res.data) {
            resolve(res.data);
        }
      }, () => {
        console.log('请求失败');
        reject('请求失败');
      });
    });
  };


// 刷新token
const refreshToken = async () => {
  const rdsUrl = getRdsUrl();
  const EXPIRES = 1000 * 60 * 2; // 提前失效前2分钟刷新
  const mainStore = useMainStore();
  const { sUser, dServerDt, idsToken } = mainStore.loginInfo
  const { expires_in, refresh_token } = idsToken; // 令牌的有效期（以秒为单位）
  // 计算令牌的过期时间
  let tokenExpirationTime = new Date(dServerDt).getTime() + (expires_in*1000);
  // 获取当前时间
  let now = new Date().getTime();
  let isExpires = tokenExpirationTime <= now + EXPIRES;
  // console.log("---------refreshToken---------", expires_in, refresh_token, sUser, dServerDt, isExpires )
  // 判断令牌是否过期
  if (isExpires) {
    // token 即将失效，更新token
    // console.log("Token is expired");
    let req = {
      sRefreshToken: refresh_token,
      userNo: sUser,
    }
    // console.log('--------store.state.loginInfo---------: ', store.state.loginInfo)
    service.enjoyShowLoading('正在刷新Token...');
    const tokenResult = await rdsRequest(rdsUrl.mbmApi, '管易通40公共', 'RefreshCenterToken', req);
    // if (tokenResult  && tokenResult.refresh_token ) {
    //   store.commit('loginInfoin', {
    //     ...store.state.loginInfo,
    //     dServerDt: dateRangUtil.formatDate(),
    //     idsToken: tokenResult
    //   })
    // }
    service.enjoyHideLoading();
  } else {
    // token 失效时间大于2分钟
    // console.log("Token is not expired");
  }
}

export {
  rdsRequest,
  rdsRequestAsync,
  refreshToken,
  getEnjoyOA,
  getEnjoyRDS,
  getRdsUrl
};
